/**
 * 阿有 email:37798955@qq.com
 * 2017-11
 */
function createDBHelp(数据库名,数据库文件名) {
	this._db =undefined;
	this._tableName = "";
	this._err = '';
	this._where = '';
	this._columns = [];
	this.check = function() {
		if(!window.openDatabase) {
			alert("不支持");
			return false;
		} else {
			this._db = openDatabase(数据库文件名, '1.0',数据库名, 50 * 1000 * 1000);
			return true;
		}
	}

	//初始化数据库，如果需要则创建表
	this.init = function(tn, model) {
		if (!this.check()) return null;
		this._tableName = tn;
		//alert(tn)
		this._columns = null;
		this._columns = [];
		for(var k in model)
			this._columns.push(k);

		if(this._columns.length > 0)
			this.createTable();
		return this;
	}
	//创建表，colums:[name:字段名,type:字段类型]
	this.createTable = function() {
		tb = this._tableName;
		var sql = "CREATE TABLE IF NOT EXISTS " + tb;
		sql = sql + " (" + this._columns.join(',') + ")";
		this._db.transaction(function(t) {
			t.executeSql(sql);
		})
	}
	this.dropTable = function() {
		tb = this._tableName
		this._db.transaction(function(t) {
			t.executeSql("drop TABLE IF EXISTS " + tb);
		})
	}
	//where语句，支持自写和以对象属性值对的形式
	this.where = function(where) {
		if(typeof where === 'object') {
			var j = this.toArray(where);
			w = j.join(' and ');
		} else if(typeof where === 'string') {
			w = where;
		}
		if(w == "")
			return null;
		this._where = " where " + w;
		return this;
	}
	this.onErr = function(tx, e) {
		this._err = e;
		alert(e.message);
		//console.log(e.message);
	}
	//查询，内部方法
	this.execSql = function(sql, valus, callback) {
		var that = this;
		var a = [];
		var success = function(tx, result) {
			if(callback) {
				callback.call(that, tx, result);
			}
		}
		this._db.transaction(function(t) {
			t.executeSql(sql, valus, success, that.onErr);
		})
	}
	this.insertObj = function(obj, callback) {
		var cols = [],
			qs = [],
			vs = [];
		for(var key in obj) {
			cols.push(key);
			qs.push('?');
			vs.push(obj[key]);
		}
		var sql = "insert into " + this._tableName + " (" + cols.join(',') + ") Values (" + qs.join(',') + ")";
		//alert(sql)
		this.execSql(sql, vs, callback)
	}
	this.updateObj = function(obj, callback) {
		var cols = [],
			vs = [];
		for(var key in obj) {
			cols.push(key + '= ? ')
			vs.push(obj[key]);
		}
		var sql = "update " + this._tableName + " set " + cols.join(',') + this._where;
		//alert(sql)
		this.execSql(sql, vs, callback)
	}
	this.saveObj = function(obj, callback) {
		var sql = "select count(1) as cnt from " + this._tableName + this._where;
		//alert(sql)
		var success = function(tx, rs) {
			if(rs.rows.length > 0 && rs.rows.item(0).cnt > 0) {
				this.updateObj(obj, callback)
			} else {
				this.insertObj(obj, callback)
			}
		};
		this.execSql(sql, [], success);
	}
	this.getRs = function(callback) {

		var that = this;
		var fs = this._columns.join(',');
		var sql = "select " + fs + " from " + this._tableName + this._where;
		var success = function(tx, rs) {
			if(callback) {
				callback.call(that, tx, rs);
			}
		};
		this.execSql(sql, [], success);
	}

	this.putV = function(obj, targetid) {
		tag = document.getElementById(targetid)
		if (tag==null)
		  return;
		if (hasClass(tag,'phtml'))
			document.getElementById(targetid).innerHTML = obj;	
		else
			document.getElementById(targetid).value = obj;
	}

	this.getN = function(targetid, def) {
		var v = this.getV(targetid);
		var i = Number(v, 10);
		if(isNaN(i)) {
			if(isNaN(def)) {
				return 0;
			} else {
				return def;
			}
		}
		return i;
	}
	this.getV = function(targetid) {
		tag = document.getElementById(targetid);
		if(tag == null)
			return ''
		var obj = '';
		if (hasClass(tag,'phtml'))
			obj = document.getElementById(targetid).innerHTML;
		else
			obj = document.getElementById(targetid).value;		
		return obj;
	}

	this.getGuid = function() {
		var d = new Date().getTime();
		var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
			var r = (d + Math.random() * 16) % 16 | 0;
			d = Math.floor(d / 16);
			return(c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
		});
		return uuid;
	}
	
}

function lookJSON(obj) {
	alert(JSON.stringify(obj))
}
//依赖于dbmanager.js
//model 在开始的时候插入createdb.html
function getModel(tablename) {
	str = localStorage.getItem(tablename)
	return JSON.parse(obj)
}

function hasClass(obj, cls) {
	var obj_class = obj.className, //获取 class 内容.
		obj_class_lst = obj_class.split(/\s+/); //通过split空字符将cls转换成数组.
	x = 0;
	for(x in obj_class_lst) {
		if(obj_class_lst[x] == cls) { //循环数组, 判断是否包含cls
			return true;
		}
	}
	return false;
}

function createMmdl() {
	var obj = {
		_tableName: "",
		_rs: [{
			_data: {},
			_where: {}
		}]
	};
	return obj;
}

function createSmdl() {
	var obj = {
		_tableName: "",
		_rs: [{
			_data: {},
			_where: {}
		}]
	};
	return obj;
}
/*
examples:
var db=createdb();
db.init('channel_list',[{name:'id',type:'integer primary key autoincrement'},{name:'name',type:'text'},{name:'link',type:'text'},{name:'cover',type:'text'},{name:'updatetime',type:'integer'},{name:'orders',type:'integer'}]);
db.init('feed_list',[{name:'parentid',type:'integer'},{name:'feed',type:'text'}]);
db.where({name:'aa'}).getData(function(result){
  console.log(result);//result为Array
});
db.where({name:'aa'}).deleteData(function(result){
  console.log(result[0]);//删除条数
});
db.where({name:'bb'}).saveObj({link:'jj'},function(result){
  console.log(result);//影响条数
})
})
*/